package com.gree.flowable.app.controller;

import com.gree.common.entity.ReturnVo;
import com.gree.common.utils.FtpUtil;
import com.gree.common.utils.ReturnCode;
import com.gree.flowable.app.tools.utils.Ftp;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author ：180849
 * @date ：Created in 2021/5/21 10:07
 * @description：http请求访问测试
 * @modified By：
 * @version: 1.0
 */
@RestController
@RequestMapping("/test")
public class MyClientTest  {


    /*@Autowired
    private MyClient myClient;

    @Autowired
    private FormInterfaceInfoMapper formInterfaceInfoMapper;

    @GetMapping("/getToken")
    public String getToken(@RequestParam("username")String username,@RequestParam("password")String password){
        String url = "http://10.2.24.238:8081/microservice-auth3/oauth/token?username="+username+"&password="+password+"&" +
                "grant_type=password&scope=server&client_id=external_client&client_secret=123456";
        String token = myClient.getToken(url);
        System.out.println(token);
        JSONObject json = (JSONObject) JSON.parse(token);
        System.out.println(json);
        String tokenAll = json.get("access_token").toString();
        System.out.println(tokenAll);
        return token;
    }

    @GetMapping("/setToken")
    public ReturnVo setToken(){
        String getTokenUrl = "http://10.2.24.238:8081/microservice-auth3/oauth2/loginGscm";
        Map<String,String> getTokenParams = new HashMap<>();
        getTokenParams.put("username","180849");
        getTokenParams.put("password","7nKjskJsWY3Qpc6az%2F2J0A%3D%3D");
        getTokenParams.put("comp","400");
        ReturnVo scmToken = myClient.getScmToken(getTokenUrl, getTokenParams);
        JSONObject tokenInfo = (JSONObject) JSON.parse(scmToken.getData().toString());
        String access_token = tokenInfo.get("access_token").toString();
        Map<String,String> heardsMap = new HashMap<>(16);
        heardsMap.put("Authorization","Bearer "+access_token);
        Map<String,Object> paramsMap = new HashMap<>(16);
        paramsMap.put("modelKey","");
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("pageNum",1);
        queryMap.put("pageSize",15);
        paramsMap.put("query",queryMap);
        paramsMap.put("tenantId","");
        String deployListUrl = "localhost:8765/flowable/model/deployList";
        ReturnVo deployList = myClient.getDeployList(deployListUrl, heardsMap, paramsMap);
        return deployList;
    }

    @PostMapping("/callBackTest")
    public void callBackTest(@RequestBody Map<String,Object> dataMap){
        QueryWrapper<FormInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FormInterfaceInfo::getInterfaceType,"1").eq(FormInterfaceInfo::getUserName,"180849");
        FormInterfaceInfo formInterfaceInfo = formInterfaceInfoMapper.selectOne(queryWrapper);
        String url = formInterfaceInfo.getInterfaceAddress();
        myClient.postCallBack(url,dataMap);
    }*/


    /**
     * 文件上传至ftp服务器
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile")
    public ReturnVo<String> uploadFileFTP(@RequestParam("filename")String fileNames, @RequestParam("file") MultipartFile file){

        ReturnVo<String> result = null;
        System.out.println(fileNames);
        if (null == file){
            return new ReturnVo<String>(ReturnCode.FAIL,"上传失败，无法找到文件！");
        }
        try{
            /* 1、配置好ftp工具类 */
            FtpUtil ftpUtil = Ftp.newInstance();

            /* 2、配置上传文件 */
            InputStream streamIn = file.getInputStream();
            // 获取上传文件全名
            String fileName = file.getOriginalFilename();
            // 配置上传保存路径
            String fpath="kbiService"+"/";
            // 生成唯一标识
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // 拿取文件名后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            // 传入文件服务器的完整文件名
            String file_name= uuid + suffix;
            /* 3、上传 */
            boolean b = ftpUtil.uploadFile(fpath, file_name, streamIn);
            if (b){
                //  将文件全名 fileName 和 uuid、suffix存进Oracle数据库里面，设置好关联关系 方便下载
                result = new ReturnVo<String>(ReturnCode.SUCCESS, "上传成功",file_name);
            }else {
                result = new ReturnVo<String>(ReturnCode.FAIL, "上传失败");
            }
        } catch (IOException e){
            result = new ReturnVo<String>(ReturnCode.FAIL, e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/downloadFile/{ftpName}/{fileName}")
    public void downloadFile(@PathVariable("ftpName")String ftpName,@PathVariable("fileName")String fileName, HttpServletResponse response) throws Exception {

//        String tntf = params.getString("tntf");//ftp文件名
//        String totf = params.getString("totf");//原文件名
        String file_path = "kbiService" + "/";
        try {
            // new 一个ftp工具
            FtpUtil ftpUtil = Ftp.newInstance();
            // 设置响应头
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // 拿取文件名后缀
            String suffix = ftpName.substring(ftpName.lastIndexOf(".")).toLowerCase();
            // 中文会在http头里乱码 这里使用加密，前端js请使用对应解密算法  这里使用的是URLEncoder
            response.addHeader("filename", URLEncoder.encode(fileName+suffix, "UTF-8"));
            // 跨平台的http响应 暴露头filename
            response.setHeader("Access-Control-Expose-Headers", "filename");
            // 开始下载文件
//            String ftpName = "ea29525394f14463aadada5e8fe00e6b" + ".xlsx";

//            ftpName = ftpName+suffix;
            ftpUtil.downloadFile(file_path, ftpName, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.setStatus(200);
            response.flushBuffer();
        }
    }

}
